package centerberg.engine;
import sun.audio.*;
import java.io.*;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;

/**
 * The class used for handling Sound files and playback
 *
 *  * @author Linus Centerström
 *
 */


public class Sound {
	private File soundFile;
	private AudioInputStream soundIn;
	private Clip clip;
	private DataLine.Info info;
	
	/**
	 * 
	 * @param filename the filename/filepath of the sound file
	 */
	public Sound(File soundFile) {
		this.soundFile = soundFile;
		try {
			soundIn = AudioSystem.getAudioInputStream(soundFile);
			AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
	                   AudioSystem.NOT_SPECIFIED,
	                   16, 2, 4,
	                   AudioSystem.NOT_SPECIFIED, true);
			 info = new DataLine.Info(Clip.class, format);
			 clip = (Clip)AudioSystem.getLine(info);
			 clip.open(soundIn);
		     
		     
		   
		} catch(Exception e) {
			e.printStackTrace();
		}
		
	}
	File getFile() {
		return soundFile;
	}
	public boolean isPlaying() {
		return clip.isRunning();
	}
	/**
	 * Plays the sound for duration
	 * starting at 0
	 * where the clip last ended
	 * if it is already playing when the method is called
	 * does nothing.
	 * @param how long to play the clip in milliseconds, 0 if full clip 
	 */

	public void play(int duration,float volume,float balance) {
		if(duration < 0 )
			throw new IllegalArgumentException("Invalid duration");
		FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
   	 	gainControl.setValue(volume);
   	 	FloatControl balanceControl = (FloatControl)clip.getControl(FloatControl.Type.PAN);
	 	balanceControl.setValue(balance);
		clip.start();
		if(duration != 0)
			try {
				Thread.sleep(duration);
			} catch(Exception e) {
				e.printStackTrace();
			}
		else
			while(clip.isRunning())
				Thread.yield();
		clip.stop();
		clip.setFramePosition(0);
		gainControl.setValue(0);
		balanceControl.setValue(0);
	}

	
}

